package top.bug.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.bug.blog.common.BasePO;
import top.bug.blog.constant.CommonConstants;
import top.bug.blog.entity.dto.common.BatchRequest;
import top.bug.blog.entity.dto.common.OrderModRequest;
import top.bug.blog.entity.dto.links.LinksAddRequest;
import top.bug.blog.entity.dto.links.LinksQueryRequest;
import top.bug.blog.entity.dto.links.LinksUpdateRequest;
import top.bug.blog.entity.po.Links;
import top.bug.blog.enums.ErrorCode;
import top.bug.blog.exception.BussinessException;
import top.bug.blog.mapper.LinksMapper;
import top.bug.blog.service.LinksService;
import top.bug.blog.utils.QueryWrapperUtils;
import top.bug.blog.utils.StrUtils;

import javax.annotation.Resource;

import static top.bug.blog.utils.StrUtils.isNotBlank;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description 友链 实现类
 */
@Service
public class LinksServiceImpl extends ServiceImpl<LinksMapper, Links> implements LinksService {
    @Resource
    private LinksMapper linksMapper;

    @Override
    public Page<Links> getList(LinksQueryRequest queryRequest) {
        Page<Links> page = new Page<>(1, 10);
        String title = queryRequest.getTitle();
        String status = queryRequest.getStatus();
        String url = queryRequest.getUrl();
        LambdaQueryWrapper<Links> queryWrapper = new LambdaQueryWrapper<Links>()
                .like(isNotBlank(title), Links::getTitle, title)
                .like(isNotBlank(url), Links::getUrl, url)
                .eq(isNotBlank(status), Links::getStatus, status);
        // 时间范围参数
        QueryWrapperUtils.addTimeRangeCondition(queryWrapper, queryRequest.getCreateTimeRange(), Links::getCreateOn);
        QueryWrapperUtils.addTimeRangeCondition(queryWrapper, queryRequest.getUpdateTimeRange(), Links::getUpdateOn);
        linksMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public Boolean add(LinksAddRequest addRequest) {
        if (null == addRequest) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        // 必填项校验
        String title = addRequest.getTitle();
        String url = addRequest.getUrl();
        if (StrUtils.isAnyBlank(title, url)) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        Links links = new Links();
        BeanUtil.copyProperties(addRequest, links);
        // 默认值填充
        links.setStatus(CommonConstants.STATUS_ENABLE);
        if (!(url.startsWith(CommonConstants.HTTP_PREFIX) || url.startsWith(CommonConstants.HTTPS_PREFIX))) {
            links.setUrl(CommonConstants.HTTP_PREFIX + url);
        }
        if (null == links.getOrderNum()) {
            links.setOrderNum(CommonConstants.DEFAULT_ORDER_NUM);
        }
        // 保存用户（唯一性由数据库层面进行控制）
        boolean save = false;
        try {
            save = this.save(links);
        } catch (DuplicateKeyException e) {
            throw new BussinessException(ErrorCode.DATA_ALREADY_EXISTED);
        }
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(BatchRequest batchRequest) {
        if (null == batchRequest || CollUtil.isEmpty(batchRequest.getIds())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        return this.removeBatchByIds(batchRequest.getIds());
    }

    @Override
    public Boolean editOrder(OrderModRequest orderModRequest) {
        if (null == orderModRequest || StrUtil.isEmpty(orderModRequest.getId()) || null == orderModRequest.getOrderNum()) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        LambdaUpdateWrapper<Links> updateWrapper = new LambdaUpdateWrapper<>();
        Integer orderNum = orderModRequest.getOrderNum();
        updateWrapper.set(Links::getOrderNum, orderNum).eq(BasePO::getId, orderModRequest.getId());
        return this.update(updateWrapper);
    }

    @Override
    public Boolean edit(LinksUpdateRequest updateRequest) {
        if (null == updateRequest || StrUtil.isEmpty(updateRequest.getId())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        Links links = new Links();
        BeanUtil.copyProperties(updateRequest, links);
        return this.updateById(links);
    }

}